<?php
namespace App\Http\Controllers;

use App\Models\ActivityApply;
use App\Models\MakerUser;
use App\Models\RoadShowApply;
use App\Models\MyMessage;
use App\Models\ActivityTag;
use App\Models\RoadshowHistory;
use App\Models\ActivityProject;
use App\Models\ActivityType;
use App\Models\Activity;
use App\Models\MakerActivity;
use App\Models\Project;
use App\Models\Maker;
use App\Models\MakerProject;
use App\Models\RoadshowProject;
use App\Models\RoleUser;
use App\Models\Tag;
use App\Models\Type;
use App\Http\Libs\Helper_Huanxin;
use App\Models\UserInfo;
use App\Models\Zone;
use App\Http\Controllers\Controller;
use App\Models\User;
use \DB;
use Auth;
// use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Facades\Request;
use App\Http\Requests\ActivityPostRequest;
use \Cache;
use \Excel;
class ActivityController extends CommonController
{

    /**
     * 活动列表。
     *
     * @return Response
     */
    public function getIndex()
    {
        $type = ActivityType::getType();
        $activities = DB::table('activity')->orderBy('recommend', 'desc')->orderBy('id', 'desc')->paginate(10);

        return view('activity.index')->with("activities", $activities)->with("actions", $this->actions)->with('type', $type);
    }

    /**
     * 执行一个搜索
     *
     */
    public function search()
    {
        $data = Request::input();

        $activities = Activity::orderBy('id', 'asc');
        if (isset($data['subject']) && $data['subject'] != '') {
            $activities->where('subject', 'like', '%' . $data['subject'] . '%');
        }

        if (isset($data['type']) && $data['type'] != '') {
            $activities->where('type', $data['type']);
        }

        if (isset($data['begin_time']) && $data['begin_time'] != '') {
            $activities->where('begin_time', '>', strtotime($data['begin_time']));
        }

        if (isset($data['end_time']) && $data['end_time'] != '') {
            $activities->where('end_time', '<', strtotime($data['end_time']));
        }

        $activities = $activities->paginate(10);
        $type = ActivityType::getType();

        return view('activity.search')->with("activities", $activities)->with("actions", $this->actions)
            ->with('types', $type)->with('subject', $data['subject'])->with('type', $data['type'])
            ->with('begin_time', $data['begin_time'])->with('end_time', $data['end_time']);
    }

    /**
     * 活动添加页面
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getCreate()
    {
        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');
        $types = ActivityType::getType();
        $users = User::all();
        $makers = Maker::get();

//     	$types = DB::table('type as t1')->join("type as t2","t1.upid","=","t2.id")->where('t2.code','activity_type')->where('t1.status',1)->select('t1.*')->get();
        return view('activity/create')->with('types', $types)->with('zoneTree', $zoneTree)->with('users', $users)->with('makers', $makers);
    }

    /**
     * 添加活动
     *
     * @return string
     */
    public function postInsert(ActivityPostRequest $request)
    {
        $data = Request::all();
        $data['apply_start_time'] = strtotime('now');
        $data['apply_end_time'] = strtotime($data['apply_end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['assemble_end_time'] = $data['is_assemble'] == 1 ? strtotime($data['assemble_end_time']) : 0;
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $maker_id = $data['maker_id'];
        $tag = $data['tag'];
        unset($data['user_search'], $data['maker_id'], $data['tag']);
        $data['is_admin'] = 1;
        $activity_id = DB::table("activity")->insertGetId($data);
        MakerActivity::create(['activity_id' => $activity_id, 'maker_id' => $maker_id, 'type' => 'organizer', 'status' => 1, 'uid' => $data['uid']]);

        if ($tag != '') {
            $existTags = Tag::lists('name')->toArray();
            $tags = explode(',', str_replace('，', ',', $tag));
            //剔除可能出现的连续两个逗号
            $tags = array_filter(
                $tags,
                function ($v) {
                    if ($v == '') {
                        return false;
                    } else {
                        return true;
                    }
                }
            );
            $tags = array_map(
                function ($v) {
                    return trim($v);
                },
                $tags
            );

            foreach ($tags as $k => $v) {
                if (!in_array(trim($v), $existTags)) {
                    $result = Tag::create(['name' => trim($v)]);
                    ActivityTag::create(['activity_id' => $activity_id, 'tag_id' => $result->id]);
                } else {
                    $result = Tag::where('name', trim($v))->first();
                    ActivityTag::create(['activity_id' => $activity_id, 'tag_id' => $result->id]);
                }
            }
        }

        // 生成二维码，并存储。
        //  if (empty($activity->qrcode_sign)) {
        $file_name = unique_id() . '.png';
        $qrcode_path = img_create('activity_id:' . $activity_id, $file_name, $this->uploadDir);
        Activity::where('id', $activity_id)->update(array('qrcode_sign' => $qrcode_path));

        if ($activity_id) {
            //自动创建一个群
            $res = Helper_Huanxin::createGroup($data['subject'],$data['summary'],'admin');
            $res =json_decode($res, true);
            Activity::where('id', $activity_id)->update(array('groupid' => $res['data']['groupid']));
            return AjaxCallbackMessage('活动添加成功', true, url('activity/index'));
//     		return $this->tip('活动添加成功',url('activity/index'),true);
        } else {
            return AjaxCallbackMessage('活动添加失败', false);
//     		return $this->tip('活动添加失败',url('activity/index'),false);
        }
    }

    /**
     * 编辑活动
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getEdit()
    {
        if (!Request::has('aid')) {
            return $this->tip('参数异常', url('activity/index'), false);
        }
        $activity_id = Request::input('aid');
        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');
        $types = ActivityType::getType();
        $users = User::all();

        $makers = Maker::get();

        $oMaker = MakerActivity::where('activity_id', $activity_id)->where('type', 'organizer')->first();

//     	$types = DB::table('type as t1')->join("type as t2","t1.upid","=","t2.id")->where('t2.code','activity_type')->where('t1.status',1)->select('t1.*')->get();
        $activity = DB::table('activity')->where('id', $activity_id)->first();
        if ($activity->zone_id) {
            $zone = DB::table('zone')->where('id', $activity->zone_id)->first();
            if ($zone->upid) {
                $activity->city_id = $zone->upid;
            } else {
                $activity->city_id = $zone->id;
                $activity->zone_id = 0;
            }
        } else {
            $activity->city_id = 0;
            $activity->zone_id = 0;
        }

        $tags = ActivityTag::with('tag')->where('activity_id', $activity_id)->get();

        $tagNames = array();
        foreach ($tags as $k => $v) {
            isset($v->tag) && $tagNames[] = $v->tag->name;
        }

        $tagNames = implode(',', $tagNames);

        return view('activity.edit')->with("activity", $activity)->with('types', $types)->with('tagNames', $tagNames)
            ->with('zoneTree', $zoneTree)->with('users', $users)->with('makers', $makers)->with('oMaker', $oMaker);
    }

    /**
     * 获取活动详情页面
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getActivitydetail()
    {
        if (!Request::has('aid')) {
            return $this->tip('参数异常', url('activity/index'), false);
        }
        $activity_id = Request::input('aid');
        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');
        $types = ActivityType::getType();
//     	$types = DB::table('type as t1')->join("type as t2","t1.upid","=","t2.id")->where('t2.code','activity_type')->where('t1.status',1)->select('t1.*')->get();
        $activity = DB::table('activity')->where('id', $activity_id)->first();
        if ($activity->zone_id) {
            $zone = DB::table('zone')->where('id', $activity->zone_id)->first();
            if ($zone->upid) {
                $activity->city_id = $zone->upid;
            } else {
                $activity->city_id = $zone->id;
                $activity->zone_id = 0;
            }
        } else {
            $activity->city_id = 0;
            $activity->zone_id = 0;
        }

        return view('activity.detail')->with("activity", $activity)->with('types', $types)->with('zoneTree', $zoneTree);
    }

    /**
     * 更新活动信息
     *
     * @return string
     */
    public function postUpdate(ActivityPostRequest $request)
    {
        $data = Request::all();
        $activity_id = $data['id'];
        $data['apply_start_time'] = strtotime($data['apply_start_time']);
        $data['apply_end_time'] = strtotime($data['apply_end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['assemble_end_time'] = $data['is_assemble'] == 1 ? strtotime($data['assemble_end_time']) : 0;
        $data['updated_at'] = time();
        $maker_id = $data['maker_id'];
        $tag = $data['tag'];

        unset($data['id'], $data['user_search'], $data['maker_id'], $data['tag']);
        $oMaker = MakerActivity::where('activity_id', $activity_id)->where('type', 'organizer')->where('status', '1')->first();
        if ($oMaker) {
            MakerActivity::where('activity_id', $activity_id)->where('type', 'organizer')->update(['maker_id' => $maker_id, 'status' => 1, 'uid' => $data['uid']]);
        } else {
            MakerActivity::create(['activity_id' => $activity_id, 'maker_id' => $maker_id, 'type' => 'organizer', 'status' => 1, 'uid' => $data['uid']]);
        }

        $old = Activity::where('id', $activity_id)->first();
        DB::table("activity")->where('id', $activity_id)->update($data);
        $new = Activity::where('id', $activity_id)->first();


        $tags = explode(',', str_replace('，', ',', $tag));
        //剔除可能出现的连续两个逗号
        $tags = array_filter(
            $tags,
            function ($v) {
                if ($v == '') {
                    return false;
                } else {
                    return true;
                }
            }
        );

        $tags = array_map(
            function ($v) {
                return trim($v);
            },
            $tags
        );

        //剔除管理员无心输入的空格
        $tags = array_map(
            function ($v) {
                return trim($v);
            },
            $tags
        );

        $nowTags = ActivityTag::with('tag')->where('activity_id', $activity_id)->get();
        $tagNames = array();
        foreach ($nowTags as $k => $v) {
            isset($v->tag) && $tagNames[] = $v->tag->name;
        }

        //获取需要删除的关键字
        $del = array_diff($tagNames, $tags);
        $delIds = array_map(
            function ($v) {
                $result = Tag::where('name', $v)->first();

                return $result->id;
            },
            $del
        );
        foreach ($delIds as $v) {
            ActivityTag::where('activity_id', $activity_id)->where('tag_id', $v)->delete();
        }

        //获取需要新增的关键字
        $add = array_diff($tags, $tagNames);
        if (count($add) != 0) {
            $existTags = Tag::lists('name')->toArray();
            foreach ($add as $k => $v) {
                if (!in_array(trim($v), $existTags)) {
                    $result = Tag::create(['name' => trim($v)]);
                    ActivityTag::create(['activity_id' => $activity_id, 'tag_id' => $result->id]);
                } else {
                    $result = Tag::where('name', trim($v))->first();
                    ActivityTag::create(['activity_id' => $activity_id, 'tag_id' => $result->id]);
                }
            }
        }

        //发站内信
        if(0==$data['status'] && 0!=$old->status){
            $m_title = '您已成功取消'.$new->subject.'活动。';
            $m_content = '您在'.date('Y年m月d日',strtotime($new->created_at->toDateTimeString())).'发布的'.$new->subject.'活动，已成功取消，请及时联系报名参会用户，避免造成误会，感谢你的配合及对无界投融的信赖。';
            $m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>活动名称：<span class="orange">'.$new->subject.'</span></p>
                                <p>活动时间：<span class="orange">'.date('Y年m月d日',$new->begin_time).'~'.date('Y年m月d日',$new->end_time).'</span></p>
                                <p>活动状态：<span class="orange">已取消</span></p>
	                            </div>
	                            <div class="borderLine"></div>';
            MyMessage::createMessage($new->uid,$m_title,'official',$m_content,$m_ext,'');

            $applys = ActivityApply::where('activity_id', $activity_id)->get();
            if(count($applys)>0){
                foreach($applys as $v){
                    $a_m_title = '很抱歉，'.$new->subject.'活动已取消。';
                    $a_m_content = '您好，您报名参加'.date('Y年m月d日',strtotime($new->created_at->toDateTimeString())).'的'.$new->subject.'活动，由于主办方'.date('Y年m月d日',strtotime($new->updated_at->toDateTimeString())).'临时取消，请重新安排自己的日程安排，以避免造成不必要的误会。感谢你的配合及对无界投融的信赖。';
                    $a_m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>活动名称：<span class="orange">'.$new->subject.'</span></p>
                                <p>活动时间：<span class="orange">'.date('Y年m月d日',$new->begin_time).'~'.date('Y年m月d日',$new->end_time).'</span></p>
                                <p>活动状态：<span class="orange">已取消</span></p>
	                            </div>
	                            <div class="borderLine"></div>';
                    MyMessage::createMessage($v->uid,$a_m_title,'official',$a_m_content,$a_m_ext,'');
                }
            }
        }


        Cache::forget('activity_baseInfo_' . $activity_id);

        return AjaxCallbackMessage('活动编辑成功', true, url('activity/index'));
    }

    /**
     * 删除活动
     *
     * @return string
     */
    public function postDelete()
    {
        if (!Request::has('aid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $aid = Request::input("aid");
        DB::table('activity')->where('id', '=', $aid)->delete();
        Cache::forget('activity_baseInfo_' . $aid);

        return AjaxCallbackMessage('活动删除成功', true, url('activity/index'));
    }

    /**
     * 活动项目列表。
     *
     * @return Response
     */
    public function getActivityprojects()
    {
        $aid = Request::input('aid');
        $datas = DB::table('activity_project as ap')->join("activity as a", "ap.activity_id", "=", "a.id")->join("project as p", "ap.project_id", "=", "p.id")->where(
            'ap.activity_id',
            intval($aid)
        )->select("ap.id", "a.subject as a_subject", "p.subject as p_subject")->paginate(10);

        return view('activity.project')->with("datas", $datas)->with("actions", $this->actions)->with("aid", $aid);
    }

    /**
     *
     * @return string
     */
    public function postProjects()
    {
        if (!Request::has('project_name')) {
            return AjaxCallbackMessage('项目名称不能为空', false);
        }
        $project_name = Request::input("project_name");
        $projects = DB::table('project')->where('subject', 'like', '%' . trim($project_name) . '%')->select('id', 'subject')->get();

        if ($projects) {
            return AjaxCallbackMessage($projects, true);
        } else {
            return AjaxCallbackMessage('没有搜索到与你输入标题相匹配的项目', false);
        }
    }

    /**
     *
     * @return string
     */
    public function postProjectinsert()
    {
        if (!Request::has('activity_id')) {
            return AjaxCallbackMessage('参数异常', false);
        }
        if (!Request::has('project_id')) {
            return AjaxCallbackMessage('请选择项目', false);
        }

        //如果改项目曾经申请过路演，那么就一定要选择路演申请编号。
        if (Request::input('show') == true && !Request::input('show_id') > 0) {
            return AjaxCallbackMessage('请选择路演申请编号', false);
        }

        $data['activity_id'] = Request::input("activity_id");
        $data['project_id'] = Request::input("project_id");
        $data['roadshow_apply_id'] = Request::input("show_id");
        $exist = ActivityProject::where('activity_id', $data['activity_id'])->where('project_id', $data['project_id'])->first();
        if (is_object($exist)) {
            return AjaxCallbackMessage('已经添加该项目，请勿重复添加！', false);
        }
        $id = DB::table('activity_project')->insertGetId($data);
        RoadshowHistory::create(array('project_id'));
        $project = Project::where('id', $data['project_id'])->first();
        $activity = Activity::where('id', $data['activity_id'])->first();

        $maker_project = MakerProject::where('project_id', $project->id)->first();

        if (isset($maker_project->maker_id)) {
            $maker_id = $maker_project->maker_id;
        } else {
            //随便获取了个活动的场地
            $maker_activity = MakerActivity::where('activity_id', $data['activity_id'])->first();
            $maker_id = $maker_activity->maker_id;
        }
        $maker = Maker::where('id', $maker_id)->first();
        $user = User::where('uid', $project->uid)->first();
        Cache::forget('activity_baseInfo_' . $data['activity_id']);

        if ($id) {
            $content_sms = trans(
                'sms.getRoadshowTicket',
                array(
                    'subject'  => $project->subject,
                    'maker'    => $maker->name,
                    'roadshow' => $activity->subject,
                    'time'     => date('Y年m月d日 H:i', $activity->begin_time)
                )
            );
            @SendSMS($user->username, $content_sms, 'getRoadshowTicket');
            $content_app = trans(
                'app.getRoadshowTicket',
                array(
                    'subject'  => $project->subject,
                    'roadshow' => $activity->subject,
                    'time'     => date('Y年m月d日 H:i', $activity->begin_time),
                    'length'   => ($activity->end_time - $activity->begin_time) / 3600,
                    'maker'    => $maker->name,
                    'kefu'     => getKefuName()
                )
            );
//            @Helper_Huanxin::sendMessage(
//                array($user->uid),
//                $content_app,
//                "admin",
//                array(
//                    'type'    => "hyperjump",
//                    'content' => getKefuContentArray()
//                )
//            );
            $time = '';
            if ($data['roadshow_apply_id']) {
                $roadshowApply = RoadShowApply::where('id', $data['roadshow_apply_id'])->first();
                $m_title='恭喜您，申请的我要路演已经通过审核';
                $m_content='你于'.date('Y年m月d日',strtotime($roadshowApply->created_at)).'申请的“我要路演”已通过，并安排至最近的无界路演。';
                $m_ext='<div class="mt10 mb10 dark2_gray">
	   	                        <p>路演活动：<span class="orange">' . $activity->subject . '</span></p>
	   	                        <p>活动时间：<span class="lightgray2">' . date('Y-m-d H:i', $activity->begin_time) . ' ~ ' . date('Y-m-d H:i', $activity->end_time) . '</span></p>
	   	                        <p>路演地点：<span class="orange">' . $maker->name . '</span></p>
	                            </div>
	                            <div class="borderLine"></div>';
                if (isset($roadshowApply->id)) {
                    $time = '于' . date('Y-m-d H:i:s', strtotime($roadshowApply->created_at));
                    if ($roadshowApply->initiator == 'project') {
                        MyMessage::createMessage($roadshowApply->uid,$m_title,'official',$m_content,$m_ext,'');
                    } else {
                        $makerUsers = MakerUser::where('maker_id', $maker_id)->get();
                        foreach ($makerUsers as $k => $v) {
                            MyMessage::createMessage($v->uid,$m_title,'official',$m_content,$m_ext,'');
                        }
                    }
                }
            }

            return AjaxCallbackMessage('项目添加成功', true);
        } else {
            return AjaxCallbackMessage('项目添加失败', false);
        }
    }

    /**
     * 根据项目id去寻找和该项目相关的路演申请id
     */
    public function postRoadShow(Request $request)
    {
        $data = Request::input();
        $lists = RoadshowProject::where('project_id', $data['project_id'])->get()->toArray();

        if (count($lists)) {
            return AjaxCallbackMessage($lists, true);
        } else {
            return AjaxCallbackMessage('没有匹配的路演申请记录', false);
        }
    }

    /**
     * 删除活动
     *
     * @return string
     */
    public function postProjectdelete()
    {
        if (!Request::has('apid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $apid = Request::input("apid");
        DB::table('activity_project')->where('id', '=', $apid)->delete();

        return AjaxCallbackMessage('活动项目删除成功', true);
    }

    /**
     *
     * 获取活动相关的创客空间
     */
    public function  getActivityMaker()
    {
        $data = Request::input();
        $oMaker = MakerActivity::where('activity_id', $data['aid'])->where('type', 'organizer')->where('status', 1)->first();
        $aMakers = MakerActivity::where('activity_id', $data['aid'])->where('type', 'assistance')->where('status', 1)->get();
        $makers = Maker::orderBy('id', 'asc')->get();
        $oMaker ? $oMakerId = $oMaker->maker_id : $oMakerId = 0;
        $aMakerIds = [];
        foreach ($aMakers as $v) {
            $aMakerIds[] = $v->maker_id;
        }

        return view('activitymaker.index')->with('oMaker', $oMakerId)->with('aMakerIds', $aMakerIds)->with('makers', $makers)->with('aid', $data['aid']);
    }

    /**
     * 编辑活动相关创客空间
     */
    public function postActivityMaker()
    {
        $data = Request::input();
        !isset($data['aMakers']) && $data['aMakers'] = [];
        if (in_array($data['oMaker'], $data['aMakers'])) {
            return AjaxCallbackMessage('主办空间和协办空间重复，请核对后重新提交', false);
        }

        MakerActivity::where('activity_id', $data['aid'])->delete();

        $data['oMaker'] != 0 && MakerActivity::firstOrCreate(['activity_id' => $data['aid'], 'maker_id' => $data['oMaker'], 'type' => 'organizer', 'status' => 1]);

        foreach ($data['aMakers'] as $v) {
            MakerActivity::firstOrCreate(['activity_id' => $data['aid'], 'maker_id' => $v, 'type' => 'assistance', 'status' => 1]);
        }

        Cache::forget('activity_baseInfo_' . $data['aid']);

        return AjaxCallbackMessage('活动相关创客空间编辑成功', true, url('activity/index'));
    }

    /**
     * 获取活动签到二维码
     */
    public function getSignCode(Request $request)
    {
        $data = Request::input();
        $activity = Activity::where('id', $data['id'])->first();

        // 生成二维码，并存储。
        //  if (empty($activity->qrcode_sign)) {
        $file_name = unique_id() . '.png';
        $qrcode_path = img_create('activity_id:' . $data['id'], $file_name, $this->uploadDir);
        Activity::where('id', $data['id'])->update(array('qrcode_sign' => $qrcode_path));
        // }
        $activity = Activity::where('id', $data['id'])->first();

//        dd($activity->qrcode_sign);

        return view('activity.sign')->with('activity', $activity)->with('id', $data['id']);
    }

    /**
     * 重新生成二维码
     */
    public function postSignCode()
    {
        $data = Request::input();
        $file_name = unique_id() . '.png';
        $qrcode_path = img_create($data['id'], $file_name, $this->uploadDir);
        Activity::where('id', $data['id'])->update(array('qrcode_sign' => $qrcode_path));

        return AjaxCallbackMessage('重新生成成功', true, url('activity/sign-code?id=' . $data['id']));
    }

    /**
     * 根据主题来搜索
     */
    public function postFind(Request $request)
    {
        $data = Request::input();
//        dd($data);
        $lists = Activity::orderBy('id', 'asc')
            ->where('subject', 'like', '%' . $data['subject'] . '%')->get();

        if (count($lists)) {
            return AjaxCallbackMessage($lists, true);
        } else {
            return AjaxCallbackMessage('没有找到匹配的活动', false);
        }
    }

    public function getExport(Request $request)
    {
        $data = Request::input();

        $lists = ActivityApply::with('maker')->where('activity_id', $data['id'])->get()->toArray();
        $activity = Activity::where('id', $data['id'])->first();

        $title = [["name" => '姓名', "tel" => '手机号', "company" => '公司', "job" => '职位', "maker" => '参会地点', "time" => '报名时间'],];

        $applyInfos = array();
        foreach ($lists as $k => $v) {
            $applyInfos[$k]['name'] = $v['name'];
            $applyInfos[$k]['tel'] = $v['tel'];

            if ('' != $v['company']) {
                $applyInfos[$k]['company'] = $v['company'];
            } else {
                $userInfo = UserInfo::where('uid', 0)->first();
                if(isset($userInfo->institution_name)){
                    $applyInfos[$k]['company'] = $userInfo->institution_name;
                }else{
                    $applyInfos[$k]['company'] = '';
                }
            }

            if ('' != $v['job']) {
                $applyInfos[$k]['job'] = $v['job'];
            } else {
                $userInfo = UserInfo::where('uid', $v['uid'])->first();
                if(isset($userInfo->job)){
                    $applyInfos[$k]['job'] = $userInfo->job;
                }else{
                    $applyInfos[$k]['job'] = '';
                }
            }

            if (isset($v['maker']['name'])) {
                $applyInfos[$k]['maker'] = $v['maker']['name'];
            } else {
                $applyInfos[$k]['maker'] = '';
            }

            $applyInfos[$k]['time'] = date('Y-m-d H:i:s', $v['created_at']);
        }

        $applyInfos = array_merge($title, $applyInfos);
//        dd($applyInfos);

        Excel::create(
            '活动“' . $activity->subject . '”的报名名单',
            function ($excel) use ($applyInfos) {
                $excel->sheet(
                    '报名名单',
                    function ($sheet) use ($applyInfos) {
                        $sheet->rows($applyInfos);
                    }
                );
            }
        )->export('xls');
    }

    /**
     * 获取统计页面
     */
    public function getStatistic(Request $request)
    {
        $data = Request::input();
        $count = ActivityApply::where('activity_id', $data['id'])->count();

        return view('activity.statistic')->with('id', $data['id'])->with('count', $count);
    }

    /**
     * 获取报名渠道分布数
     */
    public function getChannel(Request $request)
    {
        $data = Request::input();
        $types = ActivityApply::where('activity_id', $data['id'])->get()->lists('type');

        $computer = $app = $weixin = $other = 0;

        foreach ($types as $k => $v) {
            if ('computer' == $v) {
                $computer += 1;
            } elseif ('app' == $v) {
                $app += 1;
            } elseif ('weixin' == $v) {
                $weixin += 1;
            } else {
                $other += 1;
            }
        }

        $arr = array('电脑端' => $computer, 'app端' => $app, '微信' => $weixin, '其他' => $other);

        echo json_encode($arr);
    }

    /**
     * 获取报名角色分布数
     */
    public function getRole(Request $request)
    {
        $data = Request::input();
        $uids = ActivityApply::where('activity_id', $data['id'])->get()->lists('uid');

        $project = $invest = $maker = $other = 0;

        foreach ($uids as $k => $v) {
            if ('0' == $v || '' == $v) {
                $other += 1;
            }

            if ($v > 0) {
                $role = RoleUser::where('uid', $v)->first();

                if (!is_object($role)) {
                    continue;
                }

                if (2 == $role->role_id) {
                    $project += 1;
                }

                if (3 == $role->role_id) {
                    $invest += 1;
                }

                if (4 == $role->role_id) {
                    $maker += 1;
                }
            }
        }

        $arr = array('项目方' => $project, '投资人' => $invest, '创客空间' => $maker, '嘉宾或游客' => $other);

        echo json_encode($arr);
    }
}